package com.atguigu.srb.sms.consumer;

import com.atguigu.srb.sms.service.SmsService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author lsyandwh
 * @create 2022-12-19 19:30
 */
@Component
public class SmsReceiver {

    @Autowired
    private SmsService smsService;

    /**
     * 创建交换机绑定队列
     * @param channel
     * @param message
     * @param str
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "rechargeQueue"),
            exchange = @Exchange(name = "rechargeExchange",type = ExchangeTypes.FANOUT),
            key = "key"
    ))
    public void sendListener(Channel channel, Message message,String str) throws IOException {

        System.out.println("message " + new String(message.getBody()));
        System.out.println("message " + str);

        //执行发送短信的操作
//        smsService.sendCode("");

        try {
            //签收消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (IOException e) {
            //拒收消息，将消息回到队列，保证消息确认消费
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
        }
    }
}
